from .models import Menu
from utils.serializers import CustomModelSerializer
from rest_framework import serializers


class WebMenuSerializer(CustomModelSerializer):
    """
    前端菜单路由-序列化器
    """
    pid = serializers.SerializerMethodField()
    meta = serializers.SerializerMethodField()

    class Meta:
        model = Menu
        exclude = ('show', 'icon', "title", 'hideChildren', 'target', 'link', 'parent')
        ordering = ('-sort',)
        read_only_fields = ['id']

    def get_meta(self, obj):
        return {"title": obj.title, "icon": obj.icon, "show": obj.show, "hideChildren": obj.hideChildren,
                "target": obj.target, "link": obj.link}

    def get_pid(self, obj):
        return obj.parent.id if obj.parent else 0


class MenuSerializer(CustomModelSerializer):
    """
    菜单管理-序列化器
    """
    children = serializers.SerializerMethodField()
    value = serializers.ReadOnlyField(source="id")

    class Meta:
        model = Menu
        fields = '__all__'
        read_only_fields = ['id']
        extra_kwargs = {'permission': {'required': False, }, 'redirect': {'required': False, }}

    def get_children(self, obj):
        if obj.children:
            return MenuSerializer(obj.children.order_by('sort'), many=True).data
        return None


class ButtonCreateSerializer(CustomModelSerializer):
    """
    按钮新增序列化器
    """
    name = serializers.CharField(default='button')
    type = serializers.IntegerField(default=2)

    class Meta:
        model = Menu
        fields = '__all__'


class ButtonSerializer(CustomModelSerializer):
    """
    按钮权限序列化器
    """

    class Meta:
        model = Menu
        fields = ('permission',)
